import os
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from program.ssqt import Ui_MainWindow  # 导入 program 中的 Ui_MainWindow 界面类
import torch
import model.res_fc as f


class MyMainWindow(QMainWindow, Ui_MainWindow):  # 继承 QMainWindow 类和 Ui_MainWindow 界面类
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)  # 初始化父类
        self.setupUi(self)  # 继承 Ui_MainWindow 界面类
        # print("初始化图形界面")
        self.pushButton.clicked.connect(self.click_calculate)

        # BASE_DIR = os.path.dirname(os.path.realpath(sys.argv[0]))
        # 检查是否在打包的环境中运行
        if getattr(sys, 'frozen', False):
            # 如果在打包环境中，模型文件会在临时目录中
            model_path = os.path.join(sys._MEIPASS, 'model.pth')
        else:
            # 如果在开发环境中，模型文件在当前目录中
            model_path = 'model.pth'
        # print("加载模型")
        self.model = f.deepLinearModel(1)
        self.model.load_state_dict(torch.load(model_path))
        self.model.to('cpu')
        self.model.eval()

    def click_calculate(self):  # 点击 Button 触发
        text_boxes = [self.rpm, self.time, self.cir, self.area, self.flow]  # 假设有多个文本框
        data_array = []

        for text_box in text_boxes:
            text = text_box.text()
            try:
                number = float(text)
                data_array.append(number)
            except ValueError:
                self.result.appendPlainText(f"输入的不是有效的数字: {text}")

        def normalize(data_array):
            data_array = torch.tensor(data_array)
            max_val = torch.tensor([4940, 100, 2728.8, 3184.5, 5876.433324])
            min_val = torch.tensor([1250, 0, 891.66, 2004.64, 3.286548504])
            data_array = (data_array - min_val) / (max_val - min_val)
            return data_array

        data_array = normalize(data_array)
        with torch.no_grad():
            result = self.model(data_array)
        result = round(result.item(), 2)
        self.result.setText(f"{result}")
        return


if __name__ == '__main__':
    app = QApplication(sys.argv)  # 在 QApplication 方法中使用，创建应用程序对象
    myWin = MyMainWindow()  # 实例化 MyMainWindow 类，创建主窗口
    myWin.show()  # 在桌面显示控件 myWin
    sys.exit(app.exec_())  # 结束进程，退出程序
